package tk.mybatis.hot;

import java.lang.reflect.Field;

import org.apache.ibatis.reflection.ReflectionException;
import org.apache.ibatis.session.Configuration;
import org.springframework.util.ClassUtils;

@SuppressWarnings({ "unchecked" })
public class Reflections {

	public static boolean isAssignableFrom(String sourceClassName, Class<?> destinationClass) {
		return isAssignableFrom(forName(sourceClassName), destinationClass);
	}

	public static boolean isAssignableFrom(Class<?> sourceClass, Class<?> destinationClass) {
		return sourceClass.isAssignableFrom(destinationClass);
	}

	public static <T> Class<T> forName(String name) {
		return forName(name, Configuration.class.getClassLoader());
	}

	public static <T> Class<T> forName(String name, ClassLoader classLoader) {
		try {
			return (Class<T>) ClassUtils.forName(name, classLoader);
		} catch (Exception e) {
			throw new ReflectionException(e);
		}
	}

	public static <T> T get(String typeName, Object obj, String name) {
		return get(forName(typeName), obj, name);
	}

	public static <T> T get(Class<?> type, Object obj, String name) {
		try {
			Field field = type.getDeclaredField(name);
			field.setAccessible(true);
			return (T) field.get(obj);
		} catch (Exception e) {
			throw new ReflectionException(e);
		}
	}
}
